//
// Create by Zeng Yun on 2018/12/25
//
// 家庭成员管理
//

package home

import (
	"adai.design/jarvis/common/log"
	"adai.design/jarvis/home/model"
	"adai.design/jarvis/member"
	"encoding/json"
	"errors"
)

type MemberManager struct {
	members []*model.Member
}

func (mm *MemberManager) findMemberById(id string) *model.Member {
	for _, m := range mm.members {
		if m.Id == id {
			return m
		}
	}
	return nil
}

// 设置家庭成员状态 离家/回家
func (mm *MemberManager) setMemberState(id string, state string) (*model.Member, error) {
	for _, m := range mm.members {
		if m.Id == id {
			if m.State != state {
				m.State = state
				return m, nil
			}
			return nil, nil
		}
	}
	return nil, errors.New("member-404-not-found")
}

// 家庭成员信息
type MemberInfo struct {
	Id      string `json:"id"`
	Role    string `json:"role"`
	Name    string `json:"name"`
	Account string `json:"account"`
	Icon    string `json:"icon"`
	State   string `json:"state,omitempty"`
}

func (mm *MemberManager) getMemberInfoById(id string) (*MemberInfo, error) {
	m := mm.findMemberById(id)
	if m == nil {
		return nil, errors.New("member-404-not-found")
	}
	account, err := member.FindAccountById(m.Id)
	if err != nil {
		return nil, err
	}

	info := &MemberInfo{
		Id:      m.Id,
		Role:    m.Role,
		Name:    account.Name,
		Account: account.Account(),
		Icon:    account.Icon,
		State:   m.State,
	}
	return info, nil
}

type MemberPost struct {
	Member string `json:"member"`
	State  string `json:"state"`
}

func (mm *MemberManager) handleMemberPkg(h *Home, pkg *member.MessagePkg) error {
	// 获取家庭成员信息
	if pkg.Msg.Path == pathMember {
		if pkg.Msg.Method == member.MsgMethodGet {
			var infos []*MemberInfo
			for _, m := range mm.members {
				info, err := mm.getMemberInfoById(m.Id)
				if err == nil {
					infos = append(infos, info)
				}
			}
			ack := &member.MessagePkg{
				Type: pkg.Type,
				Ctx:  pkg.Ctx,
				Msg: &member.Message{
					Path:   pathMember,
					Method: member.MsgMethodGet,
					State:  "ok",
				},
			}
			ack.Msg.Data, _ = json.Marshal(infos)
			log.Info("data <<< %s", ack.Msg.Data)
			h.replyMemberResult(ack)
		}
		return nil
	}

	// 家庭成员位置信息
	if pkg.Msg.Path == pathMemberLocation {
		if pkg.Msg.Method == member.MsgMethodPost {
			var post MemberPost
			if err := json.Unmarshal(pkg.Msg.Data, &post); err != nil {
				log.Error("%s", err)
				return err
			}

			ack := &member.MessagePkg{
				Type: pkg.Type,
				Ctx:  pkg.Ctx,
				Msg: &member.Message{
					Path:   pkg.Msg.Path,
					Method: member.MsgMethodPost,
				},
			}
			// 更新家庭成员位置信息
			m, err := mm.setMemberState(post.Member, post.State)
			if err != nil {
				ack.Msg.State = err.Error()
			} else {
				ack.Msg.State = "ok"
			}
			h.replyMemberResult(ack)

			if m != nil {
				h.updateMemberState(m)
			}
		}
		return nil
	}
	return nil
}

// todo 家庭成员的加入与离开
